package com.iweipan.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.iweipan.R;
import com.iweipan.base.WPBaseActivity;
import com.iweipan.base.WPUrlBase;
import com.iweipan.utils.snackbar.SnackbarUtil;
import com.iweipan.view.JoinClickableSpan;
import com.iweipan.view.PeopleClickableSpan;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2016/11/10.
 */

public class RegisterActivity extends WPBaseActivity implements TextWatcher, CompoundButton.OnCheckedChangeListener {


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.materialedittext)
    MaterialEditText materialedittext;
    @BindView(R.id.num_materialedittext)
    MaterialEditText numMaterialedittext;
    @BindView(R.id.yanzheng_materialedittext)
    MaterialEditText yanzhengMaterialedittext;
    @BindView(R.id.yanzhengma)
    TextView yanzhengma;
    @BindView(R.id.checkBox)
    CheckBox checkBox;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.register)
    Button register;
    @BindView(R.id.login)
    Button login;
    private boolean isSendCode = true;
    private int codeTime = 60;


    @Override
    public int bindLayout() {
        return R.layout.activity_register;
    }

    @Override
    public void initToolbarColor() {
        color = getResources().getColor(R.color.actionbar_title_bg);
        statusBarAlpha = 60;
    }


    @Override
    public void initView(View view) {

        initTitle();

        initAgreement();

        initThings();

    }

    private void initThings() {
        materialedittext.addTextChangedListener(this);
        numMaterialedittext.addTextChangedListener(this);
        yanzhengMaterialedittext.addTextChangedListener(this);
        checkBox.setOnCheckedChangeListener(this);

    }

    /**
     * 初始化协议页面
     */
    private void initAgreement() {
        String 哈贵客户协议 = "哈贵客户协议";
        String 哈贵入市交易协议 = "哈贵入市交易协议";
        SpannableString spString = new SpannableString(哈贵客户协议);
        SpannableString spannableString = new SpannableString(哈贵入市交易协议);
        ClickableSpan peopleClickableSpan = new PeopleClickableSpan(哈贵客户协议, this, null);
        ClickableSpan joinClickableSpan = new JoinClickableSpan(哈贵客户协议, this, null);
        spString.setSpan(peopleClickableSpan, 0, 哈贵客户协议.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(joinClickableSpan, 0, 哈贵入市交易协议.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        textView2.setText(R.string.register_text_01);
        textView2.append(spString);
        textView2.append("和");
        textView2.append(spannableString);
        textView2.append("。");
        textView2.setHighlightColor(getResources().getColor(android.R.color.transparent));
        textView2.setMovementMethod(LinkMovementMethod.getInstance());
        register.setEnabled(false);
    }

    /**
     * 设置toolbar与标题
     */
    private void initTitle() {
        toolbar.setTitle("");
        toolbar.setNavigationIcon(R.drawable.back_title);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//        Typeface typeFace = Typeface.createFromAsset(getAssets(), "fonts/Roboto-LightItalic.ttf");
//        text.setTypeface(typeFace);


    }

    @Override
    public void doBusiness(Context mContext) {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    @Override
    public void resume() {
    }


    @Override
    public void destroy() {

    }


    @OnClick({R.id.register, R.id.login, R.id.yanzhengma})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.register:
                initRegister();
                break;
            case R.id.login:
                Intent intent = new Intent(getContext(), LoginActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.yanzhengma:
                sendCode();
                break;
        }
    }

    private void sendCode() {
        if (materialedittext.getText().length() != 11) {
            SnackbarUtil.shortMake(numMaterialedittext, "请输入11位手机号码").show();
            return;
        }
        OkHttpUtils.get()
                .url(WPUrlBase.SEND_AUTH_CODE)
                .addParams("mobile", materialedittext.getText().toString())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        SnackbarUtil.shortMake(numMaterialedittext, "请稍后再试").show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String info = jsonObject.getString("info");
                            int anInt = jsonObject.getInt("ret");
                            if (anInt == -1) {
                                SnackbarUtil.shortMake(numMaterialedittext, info).show();
                            } else if (anInt == 0) {
                                SnackbarUtil.shortMake(numMaterialedittext, "发送成功请注意接听电话").show();
                                changeBtnGetCode();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                });
    }

    private void initRegister() {
        numMaterialedittext.clearFocus();
        if (numMaterialedittext.getText().length() < 6) {
            SnackbarUtil.shortMake(numMaterialedittext, "请输入6位及以上密码").show();
            return;
        }

        OkHttpUtils.get()
                .url(WPUrlBase.REGISTER)
                .addParams("mobile", materialedittext.getText().toString())
                .addParams("password", numMaterialedittext.getText().toString())
                .addParams("code", yanzhengMaterialedittext.getText().toString())
                .addParams("channel", "app")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        SnackbarUtil.shortMake(numMaterialedittext, "连接超时请稍后再试").show();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            Log.e("RegisterActivity", response);
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.getInt("ret") == 0) {
                                SnackbarUtil.shortMake(login, "注册成功").show();
                                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                                intent.putExtra("from", "RegisterActivity");
                                intent.putExtra("mobile", materialedittext.getText().toString());
                                intent.putExtra("password", numMaterialedittext.getText().toString());
                                startActivity(intent);
                                finish();
                            } else {
                                String info = jsonObject.getString("info");
                                SnackbarUtil.shortMake(login, info).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }


    private void changeBtnGetCode() {
        Thread thread = new Thread() {
            @Override
            public void run() {
                if (isSendCode) {
                    while (codeTime > 0) {
                        codeTime--;
                        if (RegisterActivity.this == null) {
                            break;
                        }

                        RegisterActivity.this
                                .runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        yanzhengma.setText("获取验证码("
                                                + codeTime + ")");
                                        yanzhengma
                                                .setClickable(false);
                                    }
                                });
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    isSendCode = false;
                }
                codeTime = 60;
                isSendCode = true;
                if (RegisterActivity.this != null) {
                    RegisterActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            yanzhengma.setText("获取验证码");
                            yanzhengma.setClickable(true);
                        }
                    });
                }
            }

            ;
        };
        thread.start();
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (yanzhengMaterialedittext.getText().length() > 0
                && numMaterialedittext.getText().length() > 0
                && materialedittext.getText().length() > 0 && checkBox.isChecked()) {
            register.setEnabled(true);
        } else {
            register.setEnabled(false);
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (yanzhengMaterialedittext.getText().length() > 0
                && numMaterialedittext.getText().length() > 0
                && materialedittext.getText().length() > 0 && isChecked) {
            register.setEnabled(true);
        } else {
            register.setEnabled(false);
        }
    }
}
